package com.base.vistter.iframe.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.base.vistter.iframe.entity.InverterDevicesPowerDay;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Date;
import java.util.List;

@Mapper
public interface InverterDevicesPowerDayMapper extends BaseMapper<InverterDevicesPowerDay> {

    @Select({"<script>",
            " SELECT * FROM ",
            " ( SELECT *, ROW_NUMBER () OVER (PARTITION BY inverter_devices_id ORDER BY report_time DESC ) AS rn ",
            " FROM inverter_devices_power_day WHERE ",
            " report_time BETWEEN #{startTime} AND #{endTime} AND is_delete = 0 ",
            " <if test='stationId != null'> AND inverter_station_id = #{stationId} </if>",
            " ) sub WHERE rn = 1 ",
            "</script>"})
    List<InverterDevicesPowerDay> getDayElectric(@Param("stationId") Integer stationId, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

    @Select("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'inverter' AND TABLE_NAME = #{tableName}")
    int checkTableExists(@Param("tableName") String tableName);

    @Select("SELECT ${column}, report_time FROM inverter_devices_power_day WHERE inverter_devices_id = #{devicesId} and is_delete = 0 and report_time BETWEEN #{startTime} AND #{endTime} order by report_time ASC")
    List<InverterDevicesPowerDay> statisticsDevices(@Param("column") String column, @Param("devicesId") Integer devicesId, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

    @Select("SELECT ${column},report_time FROM ${tableName} WHERE inverter_devices_id = #{devicesId} and is_delete = 0 and report_time BETWEEN #{startTime} AND #{endTime} order by report_time ASC")
    List<InverterDevicesPowerDay> statisticsDevicesHistroy(@Param("column") String column, @Param("devicesId") Integer devicesId, @Param("tableName") String tableName, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

    @Select({"<script>",
    "SELECT SUM(dp) as dp , report_time from ${tableName} where is_delete = 0 ",
    " <if test='stationId != null'> AND inverter_station_id = #{stationId} </if>",
    " and report_time BETWEEN #{startTime} AND #{endTime} GROUP BY report_time ORDER BY report_time ASC",
    "</script>"})
    List<InverterDevicesPowerDay> statisticsStation(@Param("stationId") Integer stationId , @Param("tableName") String tableName, @Param("startTime") Date startTime, @Param("endTime") Date endTime);


}
